<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// 导入基础数据
class Import extends BaseController {

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        $this->admin_init();
        // 如果是超管，就跳转到超管的控制器
        if($this->userType != USER_TYPE_SCHOOL && $this->userType != USER_TYPE_TEACHER) redirect(admin_url("login"));
        // 加载库
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('contentModel');
        $this->load->model('dataModel');
        $this->load->model('staffModel');

        $this->load->library('PHPExcel');
        $this->baseParams = array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'is_delete' => 0
        );
        $this->deleteData = array(
            'is_delete' => 1,
            'updatetime' => date('Y-m-d H:i:s') 
        );
    }

    // 导入课室
    public function import_classroom() {
        $excelData = $this->_get_excel_data('课室名称');
        $data = array();
        foreach($excelData as $item) {
            $data[] = array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'classroom_name' => trim($item[0]),
                'is_delete' => 0,
                'updatetime' => date('Y-m-d H:i:s') 
            );
        }
        // 获取本校全部课室
        $roomParams['schoolId'] = $this->rmxSchool['id'];
        $roomParams['campusId'] = $this->campusInfo['id'];
        $roomParams['isDelete'] = 0;
        $roomList = $this->classesModel->get_classroom_list($roomParams);
        $roomList = array_value_to_key($roomList, 'classroom_name');
        // 遍历接口所有数据
        $insertRoomBatch = $updateRoomBatch = array();
        foreach($data as $item) {
            // 更新还是新增
            if(isset($roomList[$item['classroom_name']])) {
                $item['id'] = $roomList[$item['classroom_name']]['id'];
                $updateRoomBatch[] = $item;
            } else {
                $item['createtime'] = date('Y-m-d H:i:s');
                $insertRoomBatch[] = $item;
            }
        }
        // 清除数据
        // $this->db->update(ClassesModel::$classroomTable, $this->deleteData, $this->baseParams);
        // 插入数据
        if(count($insertRoomBatch)) {
            $this->db->insert_batch(ClassesModel::$classroomTable, $insertRoomBatch);
        }
        if(count($updateRoomBatch)) {
            $this->db->update_batch(ClassesModel::$classroomTable, $updateRoomBatch, 'id');
        }
        $msg = '导入成功，';
        $msg .= '插入了' . count($insertRoomBatch). '条数据';

        $this->add_log('导入课室，插入了'. count($insertRoomBatch). '条数据');

        exit(json($msg, true));
    }

    // 导入年级
    public function import_grade() {
        $excelData = $this->_get_excel_data('所属年级');
        $data = array();
        foreach($excelData as $item) {
            // 默认年级名称
            $defaultGradeName = trim($item[0]);
            // 入学年份
            $yearOfAdmission = trim($item[2]);
            // 获取默认年级信息
            $defaultGradeInfo = $this->classesModel->get_default_grade_info_by_name($defaultGradeName);
            if(empty($defaultGradeInfo)) {
                throw new Exception($defaultGradeName . '：所属年级不存在');
            }
            // 获取学段信息
            $periodInfo = $this->classesModel->get_grade_period_info($defaultGradeInfo['period_id']);
            if(empty($periodInfo)) {
                throw new Exception($defaultGradeName . '：对应的学段不存在');
            }
            // 校验年份格式
            if($yearOfAdmission && preg_match('/^\d{4}$/', $yearOfAdmission) === 0) {
                throw new Exception('入学年份格式不正确');
            }
            // 获取排序值
            $sortLevel = isset($item[3]) && is_numeric($item[3]) ? trim($item[3]) : 0;
            $data[] = array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'grade_name' => trim($item[1]),
                'default_grade_id' => $defaultGradeInfo['id'],
                'period_id' => $periodInfo['id'],
                'year_of_admission' => $yearOfAdmission,
                'sort_level' => $sortLevel,
                'is_delete' => 0,
                'updatetime' => date('Y-m-d H:i:s') 
            );
        }
        // 获取本校全部年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $gradeList = $this->classesModel->get_grade_list($gradeParams);
        $gradeList = array_value_to_key($gradeList, 'grade_name');
        //获取全部行政班信息接口
        $insertGradeBatch = $updateGradeBatch = array();
        foreach($data as $item) {
            // 更新还是新增
            if(isset($gradeList[$item['grade_name']])) {
                $item['id'] = $gradeList[$item['grade_name']]['id'];
                $updateGradeBatch[] = $item;
            } else {
                $item['createtime'] = date('Y-m-d H:i:s');
                $insertGradeBatch[] = $item;
            }
        }
        // 清除数据
        // $this->db->update(ClassesModel::$gradeTable, $this->deleteData, $this->baseParams);
        // 插入数据
        if(count($insertGradeBatch)) {
            $this->db->insert_batch(ClassesModel::$gradeTable, $insertGradeBatch);
        }
        if(count($updateGradeBatch)) {
            $this->db->update_batch(ClassesModel::$gradeTable, $updateGradeBatch, 'id');
        }

        $msg = '导入成功，';
        $msg .= '插入了' . count($insertGradeBatch). '条数据';

        $this->add_log('导入年级，插入了'. count($insertGradeBatch). '条数据');

        exit(json($msg, true));
    }
    // 导入科目
    public function import_subject() {
        // lesson表没有campusid
        $this->baseParams = array(
            'school_id' => $this->rmxSchool['id'],
            'is_delete' => 0
        );

        $excelData = $this->_get_excel_data('科目名称');
        $data = array();
        foreach($excelData as $item) {
            $data[] = array(
                'school_id' => $this->rmxSchool['id'],
                // 'campus_id' => $this->campusInfo['id'],
                'lesson_name' => trim($item[0]),
                // 截取第一个字符
                'lesson_short_name' => mb_substr(trim($item[0]), 0 , 1),
                'is_delete' => 0,
                'updatetime' => date('Y-m-d H:i:s') 
            );
        }
        // 获取本校全部科目
        $lessonParams['schoolId'] = $this->rmxSchool['id'];
        $lessonParams['isDelete'] = 0;
        $lessonList = $this->schoolModel->get_lesson_list($lessonParams);
        $lessonList = array_value_to_key($lessonList, 'lesson_name');
        // 获取接口所有科目列表
        $insertLessonBatch = $updateLessonBatch = array();
        foreach($data as $item) {
            // 更新还是新增
            if(isset($lessonList[$item['lesson_name']])) {
                $item['id'] = $lessonList[$item['lesson_name']]['id'];
                $updateLessonBatch[] = $item;
            } else {
                $item['createtime'] = date('Y-m-d H:i:s');
                $insertLessonBatch[] = $item;
            }
        }
        // 清除数据
        // $this->db->update(schoolModel::$schoolLessonTable, $this->deleteData, $this->baseParams);
        // 插入数据
        if(count($insertLessonBatch)) {
            $this->db->insert_batch(schoolModel::$schoolLessonTable, $insertLessonBatch);
        }
        if(count($updateLessonBatch)) {
            $this->db->update_batch(schoolModel::$schoolLessonTable, $updateLessonBatch, 'id');
        }

        $msg = '导入成功，';
        $msg .= '插入了' . count($insertLessonBatch). '条数据';
        
        $this->add_log('导入科目，插入了'. count($insertLessonBatch). '条数据');

        exit(json($msg, true));
    }
    // 导入教师
    public function import_teacher() {
        // user表没有campusid
        $this->baseParams = array(
            'school_id' => $this->rmxSchool['id'],
            'user_type' => USER_TYPE_TEACHER,
            'is_delete' => 0
        );
        $excelData = $this->_get_excel_data('教师名称');
        // 获取教师角色
        // $role = $this->staffModel->get_role_id_by_name($this->rmxSchool['id'], '教师');
        // // 如为空先设置教师权限数据
        // if(empty($role)) {
        //     $this->db->insert(StaffModel::$roleTable, array(
        //         'school_id' => $this->rmxSchool['id'],
        //         'role_name' => '教师',
        //         'role_parent_id' => 0,
        //         'role_parent_tree' => '0',
        //         'role_menu' => '',
        //         'is_delete' => 0,
        //         'createtime' => date('Y-m-d H:i:s'),
        //         'updatetime' => date('Y-m-d H:i:s')
        //     ));
        //     $roleId = $this->db->insert_id();
        // } else {
        //     $roleId = $role['id'];
        // }
        // 获取本校全部学生
        $studentParams['schoolId'] = $this->rmxSchool['id'];
        $studentParams['campusId'] = $this->campusInfo['id'];
        $studentParams['isDelete'] = 0;
        $studentList = $this->schoolModel->get_student_list($studentParams);
        $studentList = array_value_to_key($studentList, 'username');
        $data = array();
        $usernameArr = array();
        foreach($excelData as $item) {
            if(empty(trim($item[0]))) {
                throw new Exception('教师名称不能为空');
            }
            // 检查手机号格式
            if(trim($item[2]) && !str_is_mobile(trim($item[2]))) throw new Exception("手机号码:" . trim($item[2]) . '格式错误');
            if(in_array(trim($item[1]), $usernameArr)) {
                throw new Exception('账号不能重复：' . trim($item[1]));
            } else {
                array_push($usernameArr, trim($item[1]));
            }
            if(isset($studentList[trim($item[1])])) {
                throw new Exception('与学生账号冲突：' . trim($item[1]));
            }
            $data[] = array(
                'school_id' => $this->rmxSchool['id'],
                // 'campus_id' => $this->campusInfo['id'],
                'realname' => trim($item[0]),
                'username' => trim($item[1]),     // 登录账号
                'mobile' => trim($item[2]),     // 联系电话
                'gender' => trim($item[3]) == '女' ? '女' : '男',     // 性别
                'user_type' => USER_TYPE_TEACHER,
                'headimgurl' => trim($item[3]) == '女' ? get_sys_img('woman.jpg') : get_sys_img('man.jpg'),
                'password' => password_hash(123456, PASSWORD_DEFAULT),
                // 'role_id_set' => $roleId,
                // 'role_id_set' => '',
                'is_delete' => 0,
                'updatetime' => date('Y-m-d H:i:s')
            );
        }

        // 获取本校全部老师
        $teacherParams['schoolId'] = $this->rmxSchool['id'];
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'username');
        // 获取接口所有教师列表
        $insertTeacherBatch = $updateTeacherBatch = array();
        foreach($data as $item) {
            // 更新还是新增
            if(isset($teacherList[$item['username']])) {
                $item['id'] = $teacherList[$item['username']]['id'];
                $updateTeacherBatch[] = $item;
            } else {
                $item['createtime'] = date('Y-m-d H:i:s');
                $item['password'] = password_hash(123456, PASSWORD_DEFAULT);
                $insertTeacherBatch[] = $item;
            }
        }
        // 清除数据
        // $this->db->update(SchoolModel::$schoolUserTable, $this->deleteData, $this->baseParams);
        // 插入数据
        if(count($insertTeacherBatch)) {
            $this->db->insert_batch(SchoolModel::$schoolUserTable, $insertTeacherBatch);
        }
        if(count($updateTeacherBatch)) {
            $this->db->update_batch(SchoolModel::$schoolUserTable, $updateTeacherBatch, 'id');
        }

        $msg = '导入成功，';
        $msg .= '插入了' . count($insertTeacherBatch). '条数据';

        $this->add_log('导入教师，插入了'. count($insertTeacherBatch). '条数据');

        exit(json($msg, true));
    }
    // 导入班级
    public function import_class() {
        $excelData = $this->_get_excel_data('班级名称');
        $data = array();
        $coachData = array();
        // echo'<pre>';var_export($excelData);exit;
        foreach($excelData as $item) {
            $className = trim($item[0]);
            $gradeName = trim($item[1]);
            $classroomName = trim($item[2]);
            $masterName = trim($item[3]);
            // 班級类型
            $classType = isset($item[8]) && trim($item[8]) && trim($item[8]) == '教学班' ? CLASSES_TYPE_TEACHING : CLASSES_TYPE_NORMAL;
            if(empty($className)) {
                throw new Exception('班级名称不能为空');
            }
          
            // 支持导入功能课室的班级
            if($gradeName == '功能课室') {
                // 获取功能课室年级
                $grade = $this->classesModel->get_grade_info_for_functional();
            } else {
                // 获取年级
                $grade = $this->classesModel->get_grade_info_by_name($gradeName, $this->rmxSchool['id'], $this->campusInfo['id']);
            }
            
            if(empty($grade)) {
                throw new Exception('年级名称：' . $gradeName . ' 不存在!');
            }
            if($classroomName) {
                $classroom = $this->classesModel->get_classroom_info_by_name($classroomName, $this->rmxSchool['id'], $this->campusInfo['id']);
                if(empty($classroom)) {
                    throw new Exception('课室名称：' . $classroomName . ' 不存在!');
                }
            } else {
                $classroom['id'] = 0;
            }
            if($masterName) {
                $teacher = $this->schoolModel->get_teacher_info_by_username($masterName, $this->rmxSchool['id']);
                if(empty($teacher)) {
                    throw new Exception('教师名称：' . $masterName . ' 不存在!');
                }
            } else {
                $teacher['id'] = 0;
            }
            // 获取排序值
            $sortLevel = isset($item[7]) && is_numeric($item[7]) ? trim($item[7]) : 0;
            $data[] = array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'grade_id' => $grade['id'],
                'classroom_id' => $classroom['id'],
                // 'class_master' => $teacher['id'],
                'class_name' => $className,
                'class_slogan' => trim($item[5]),
                'class_content' => trim($item[6]),
                'class_word' => trim($item[4]),
                'class_type' => $classType,
                'sort_level' => $sortLevel,
                'is_delete' => 0,
                'updatetime' => date('Y-m-d H:i:s') 
            );
            // 导入执教关系（行政班才设置班主任）
            if($classType == CLASSES_TYPE_NORMAL) {
                if($teacher['id']) {
                    $coachData[] = array(
                        'school_id' => $this->rmxSchool['id'],
                        'campus_id' => $this->campusInfo['id'],
                        'teacher_id' => $teacher['id'],
                        'class_name' => $className,
                        'coach_type' => COACH_TYPE_MASTER,
                        'is_delete' => 0,
                        'updatetime' => date('Y-m-d H:i:s'),
                        'createtime' => date('Y-m-d H:i:s') 
                    );
                } else {
                    $deleteCoachData[] = array(
                        'class_name' => $className,
                    );
                }
            }
        }
        // 获取本校全部班级
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'class_name');
        $insertClassBatch = $updateClassBatch = array();
        foreach($data as $item) {
            // 更新还是新增
            if(isset($classList[$item['class_name']])) {
                $item['id'] = $classList[$item['class_name']]['id'];
                $updateClassBatch[] = $item;
            } else {
                $item['createtime'] = date('Y-m-d H:i:s');
                $insertClassBatch[] = $item;
            }
        }
        // 清除数据
        // $this->db->update(ClassesModel::$classTable, $this->deleteData, $this->baseParams);
        // 插入数据
        if(count($insertClassBatch)) {
            $this->db->insert_batch(ClassesModel::$classTable, $insertClassBatch);
        }
        if(count($updateClassBatch)) {
            $this->db->update_batch(ClassesModel::$classTable, $updateClassBatch, 'id');
        }
        // 插入班级数据后，获取本校全部班级
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'class_name');
        // // 获取任教关系列表
        // $coachParams['schoolId'] = $this->rmxSchool['id'];
        // $coachParams['campusId'] = $this->campusInfo['id'];
        // $coachParams['isDelete'] = 0;
        // $coachParams['coachType'] = COACH_TYPE_MASTER;
        // $coachList = $this->staffModel->get_coach_list($coachParams);
        // $coachList = array_value_to_key($coachList, 'class_id');
        // var_export($coachList);exit;
        if(isset($coachData)) {
            foreach($coachData as $coach) {
                if(isset($classList[$coach['class_name']])) {
                    $classId = $classList[$coach['class_name']]['id'];
                    $coach['class_ids'] = $classId;
                    unset($coach['class_name']);
                    // 判断该班级是否已设置班主任
                    $coachExist = $this->staffModel->get_master_coach_by_class($classId);
                    if($coachExist) {
                        if($coachExist['teacher_id'] != $coach['teacher_id']) {
                            if($coachExist['class_ids'] == $classId) {
                                // 更新
                                $this->db->update(StaffModel::$coachTable, $coach, array(
                                    'class_ids' => $classId,
                                    'coach_type' => COACH_TYPE_MASTER,
                                    'is_delete' => 0
                                ));
                            } else {
                                $idArr = explode(',', $coachExist['class_ids']);
                                foreach($idArr as $key => $id) {
                                    if($id == $classId) {
                                        unset($idArr[$key]);
                                    }
                                }
                                // 更新
                                $this->db->update(StaffModel::$coachTable, array(
                                    'class_ids' => implode(',', $idArr),
                                    'updatetime' => date('Y-m-d H:i:s')
                                ), array(
                                    'id' => $coachExist['id']
                                ));
                                 // 插入
                                $this->db->insert(StaffModel::$coachTable, $coach);
                            }
                        }
                    } else {
                        // 插入
                        $this->db->insert(StaffModel::$coachTable, $coach);
                    }
                }
            }
        }
        // 暂不删除，以防导入班级数据后，手动录入班主任后再次导入，删除掉了手动录入的数据
        // if(isset($deleteCoachData)) {
        //     foreach($deleteCoachData as $coach) {
        //         $classId = $classList[$coach['class_name']]['id'];
        //         // 判断该班级是否已设置班主任
        //         $coachExist = $this->staffModel->get_master_coach_by_class($classId);
        //         if($coachExist) {
        //             if($coachExist['class_ids'] == $classId) {
        //                 $this->db->update(StaffModel::$coachTable, array(
        //                     'is_delete' => 1,
        //                     'updatetime' => date('Y-m-d H:i:s')
        //                 ), array(
        //                     'id' => $coachExist['id']
        //                 ));
        //             } else {
        //                 $idArr = explode(',', $coachExist['class_ids']);
        //                 foreach($idArr as $key => $id) {
        //                     if($id == $classId) {
        //                         unset($idArr[$key]);
        //                     }
        //                 }
        //                 // 更新
        //                 $this->db->update(StaffModel::$coachTable, array(
        //                     'class_ids' => implode(',', $idArr),
        //                     'updatetime' => date('Y-m-d H:i:s')
        //                 ), array(
        //                     'id' => $coachExist['id']
        //                 ));
        //             }
        //         }
        //     }
        // }

        $msg = '导入成功，';
        $msg .= '插入了' . count($insertClassBatch). '条数据';

        $this->add_log('导入班级，插入了'. count($insertClassBatch). '条数据');

        exit(json($msg, true));
    }
    // 导入学生
    public function import_student() {
        $excelData = $this->_get_excel_data('学生名称');
        // 获取本校全部老师
        $teacherParams['schoolId'] = $this->rmxSchool['id'];
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'username');
        $data = array();
        $usernameArr = array();
        $seatnoArr = array();
        $realcardArr = array();
        // 获取全校班级，包含教学班
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'class_name');
        foreach($excelData as $item) {
            if(empty(trim($item[0]))) {
                throw new Exception('学生名称不能为空');
            }
            $className = trim($item[1]);
            // 获取班级
            if(isset($classList[$className])) {
                $class = $classList[$className];
            } else {
                throw new Exception('班级名称：' . $className . ' 不存在!');
            }

            // 教学班
            $teachingClassNameStr = trim($item[7]);
            $teachingClassIdArr = array();
            if($teachingClassNameStr) {
                $teachingClassNameArr = explode('/', $teachingClassNameStr);
                foreach($teachingClassNameArr as $teachingClassName) {
                    if(isset($classList[$teachingClassName]) && $classList[$teachingClassName]['class_type'] == CLASSES_TYPE_TEACHING) {
                        array_push($teachingClassIdArr, $classList[$teachingClassName]['id']);
                    } else {
                        throw new Exception('教学班：' . $teachingClassName . ' 不存在!');
                    }
                }
            }
            $teacherClassIdStr = implode(',', $teachingClassIdArr);
            if(in_array(trim($item[2]), $usernameArr)) {
                throw new Exception('学号不能重复：' . trim($item[2]));
            } else {
                array_push($usernameArr, trim($item[2]));
            }
            if(isset($teacherList[trim($item[2])])) {
                throw new Exception('与教师账号冲突：' . trim($item[2]));
            }
            if(!empty(trim($item[3])) && in_array(trim($item[3]), $realcardArr)) {
                throw new Exception('物理卡号不能重复：' . trim($item[3]));
            } else {
                array_push($realcardArr, trim($item[3]));
            }
            $data[] = array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'class_id' => $class['id'],
                'teaching_class_id' => $teacherClassIdStr,
                'realname' => trim($item[0]),
                'username' => trim($item[2]),
                'realcard' => trim($item[3]) ,
                'gender' => trim($item[4]) == '女' ? '女' : '男',
                'headimgurl' => trim($item[4]) == '女' ? UP_URL . "default/girl.jpg" : UP_URL . "default/boy.jpg",
                'job' => trim($item[5]),
                'seat_no' => trim($item[6]),
                'is_delete' => 0,
                'updatetime' => date('Y-m-d H:i:s') 
            );
        }
        // 获取本校全部学生
        $studentParams['schoolId'] = $this->rmxSchool['id'];
        $studentParams['campusId'] = $this->campusInfo['id'];
        $studentParams['isDelete'] = 0;
        $studentList = $this->schoolModel->get_student_list($studentParams);
        $studentList = array_value_to_key($studentList, 'username');
        $insertStudentBatch = $updateStudentBatch = array();
        $defaultPwd = password_hash(123456, PASSWORD_DEFAULT);
        // 闸机任务学生列表
        $gateStudentArr = array();
        foreach($data as $item) {
            // 更新还是新增
            if(isset($studentList[$item['username']])) {
                $item['id'] = $studentList[$item['username']]['id'];
                $updateStudentBatch[] = $item;

                 // 闸机任务学生列表
                 // 卡号改变才添加任务
                 if($item['realcard'] != $studentList[$item['username']]['realcard']) {
                    $gateStudentArr[] = array(
                        'realcard' => $item['realcard'],
                        'old_realcard' => $studentList[$item['username']]['realcard'],
                        'face_image' => $studentList[$item['username']]['face_image'],
                        'realname' => $studentList[$item['username']]['realname'],
                        'username' => $item['username']
                    );
                }
            } else {
                $item['createtime'] = date('Y-m-d H:i:s');
                $item['password'] = $defaultPwd;
                $insertStudentBatch[] = $item;

                // 闸机任务学生列表
                if($item['realcard']) {
                    $gateStudentArr[] = array(
                        'realcard' => $item['realcard'],
                        'old_realcard' => '',
                        'face_image' => '',
                        'realname' => $item['realname'],
                        'username' => $item['username']
                    );
                }
            }
        }
        // 清除数据
        // $this->db->update(SchoolModel::$schoolStudentTable, $this->deleteData, $this->baseParams);
        // 插入数据
        if(count($insertStudentBatch)) {
            $this->db->insert_batch(SchoolModel::$schoolStudentTable, $insertStudentBatch);
        }
        if(count($updateStudentBatch)) {
            $this->db->update_batch(SchoolModel::$schoolStudentTable, $updateStudentBatch, 'id');
        }

        $msg = '导入成功，';
        $msg .= '插入了' . count($insertStudentBatch). '条数据';

        $this->add_log('导入学生，插入了'. count($insertStudentBatch). '条数据');

        // 插入闸机任务
        $gateParams['schoolId'] = $this->rmxSchool['id'];
        $gateParams['campusId'] = $this->campusInfo['id'];
        // 过滤软删除
        $gateParams['isDelete'] = 0;
        $gateList = $this->schoolModel->get_gate_list($gateParams);
        if($gateList) {
            $insertTaskBatch = array();
            // 获取本校全部学生
            $studentParams['schoolId'] = $this->rmxSchool['id'];
            $studentParams['campusId'] = $this->campusInfo['id'];
            $studentParams['isDelete'] = 0;
            $studentList = $this->schoolModel->get_student_list($studentParams);
            $studentList = array_value_to_key($studentList, 'username');
            foreach($gateList as $gate) {
                foreach($gateStudentArr as $gateStudent) {
                    if($gateStudent['realcard']) {
                        if($gateStudent['face_image'] || $gateStudent['old_realcard']) {
                            // 更新
                            $taskType = GATE_TASK_TYPE_UPDATE;
                        } else {
                            // 新增
                            $taskType = GATE_TASK_TYPE_ADD;
                        }
                    } else {
                        if($gateStudent['face_image']) {
                            // 更新
                            $taskType = GATE_TASK_TYPE_UPDATE;
                        } else {
                            // 删除
                            $taskType = GATE_TASK_TYPE_DELETE;
                        }
                    }

                    if(isset($studentList[$gateStudent['username']])) {
                        $arr = $this->schoolModel->format_gate_task($this->rmxSchool['id'], $this->campusInfo['id'], $gate['id'], $gate['device_sn'], $studentList[$gateStudent['username']]['id'],
                            $gateStudent['realname'], $gateStudent['face_image'], GATE_USER_TYPE_STUDENT, $taskType, GATE_TASK_STATE_NEW, $gateStudent['realcard']);
                        array_push($insertTaskBatch, $arr);
                    }
                }
            }
            if($insertTaskBatch) {
                // 插入闸机任务
                $this->schoolModel->insert_gate_task_batch($insertTaskBatch);
            }
        }

        exit(json($msg, true));
    }
    // 导入考场安排
    public function import_exam() {
        $excelData = $this->_get_excel_data('考场名称', '场次');
        $roomData = array();
        $detailData = array();
        // 考场名称不可重复
        $roomNameDataArr = array();
        foreach($excelData as $item) {
            $examroomName = trim($item[0]);
            $timeslot = (int) $item[1] - 1;
            $gradeName = trim($item[2]);
            $subjectName = trim($item[3]);
            $date = trim($item[4]);
            $begin = trim($item[5]);
            $end = trim($item[6]);
            $classroomName = trim($item[7]);
            $insideTeacherStr = trim($item[8]);

            // 考场名称不可重复
            if(in_array($examroomName, $roomNameDataArr)) {
                throw new Exception('考场名称：' . $examroomName . ' 不可重复!');
            } else {
                array_push($roomNameDataArr, $examroomName);
            }

            // 获取年级
            $grade = $this->classesModel->get_grade_info_by_name($gradeName, $this->rmxSchool['id'], $this->campusInfo['id']);
            if(empty($grade)) {
                throw new Exception('年级名称：' . $gradeName . ' 不存在!');
            }
            // 获取课室
            $classroom = $this->classesModel->get_classroom_info_by_name($classroomName, $this->rmxSchool['id'], $this->campusInfo['id']);
            if(empty($classroom)) {
                throw new Exception('课室名称：' . $classroomName . ' 不存在!');
            }
            // 获取科目
            $subject = $this->schoolModel->get_lesson_info_by_name($subjectName, $this->rmxSchool['id']);
            if(empty($subject)) {
                throw new Exception('科目名称：' . $subjectName . ' 不存在!');
            }
            // 获取教师
            $teacherIdArr = array();
            $teacherNameArr = explode('、', $insideTeacherStr); 
            foreach($teacherNameArr as $name) {
                $teacher = $this->schoolModel->get_teacher_info_by_username($name, $this->rmxSchool['id']);
                if(empty($teacher)) {
                    throw new Exception('教师名称：' . $name . ' 不存在!');
                }
                array_push($teacherIdArr, $teacher['id']);
            }
            $insideTeacherIdStr = implode(',', $teacherIdArr);
            $roomData[] = array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'grade_id' => $grade['id'],
                'lesson_id' => $subject['id'],
                'type' => EXAM_TYPE_MAJOR,      // 默认为必考
                'day' => $date,
                'begin' => $begin,
                'end' => $end,
                'timeslot' => $timeslot,
                'part_of_day' => get_part_of_day($begin),
                'room_name' => $examroomName,
                'is_delete' => 0,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s') 
            );
            $detailData[] = array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'location_id' => $classroom['id'],
                'room_name' => $examroomName,
                'inside_teachers' => $insideTeacherIdStr,
                'is_delete' => 0,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s'),
                'grade_id' => $grade['id'],
                'lesson_id' => $subject['id'],
                'day' => $date,
                'begin' => $begin,
                'end' => $end,
            );
         }
        // 清除数据
        // $this->db->update(DataModel::$examTable, $this->deleteData, $this->baseParams);
        // $this->db->update(DataModel::$examRoomTable, $this->deleteData, $this->baseParams);
        // $this->db->update(DataModel::$examRoomDetailTable, $this->deleteData, $this->baseParams);
        // 插入考试数据
        $this->db->insert(DataModel::$examTable, array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'is_delete' => 0,
            'title' => '录入日期' . date('Y-m-d'),
            'createtime' => date('Y-m-d H:i:s'),
            'updatetime' => date('Y-m-d H:i:s')
        ));
        $examId = $this->db->insert_id();
        foreach($roomData as &$item) {
            $item['exam_id'] = $examId;
        }
        // 插入考场数据
        $this->db->insert_batch(DataModel::$examRoomTable, $roomData);
        foreach($detailData as &$item) {
            // 查询考场
            $params = array(
                'schoolId' => $item['school_id'],
                'campusId' => $item['campus_id'],
                'gradeId' => $item['grade_id'],
                'lessonId' => $item['lesson_id'],
                'day' => $item['day'],
                'begin' => $item['begin'],
                'end' => $item['end'],
                'roomName' => $item['room_name'],
                'isDelete' => 0
            );
            $room = $this->dataModel->get_exam_room_info($params);
            if(empty($room)) {
                throw new Exception('考场：' . $detailData['room_name'] . ' 不存在');
            }

            $item['room_id'] = $room['id'];
            unset($item['grade_id']);
            unset($item['lesson_id']);
            unset($item['day']);
            unset($item['begin']);
            unset($item['end']);
        }
        // 插入考场详情数据
        $this->db->insert_batch(DataModel::$examRoomDetailTable, $detailData);
        $msg = '导入成功，';
        $msg .= '插入了' . count($detailData). '条数据';
        
        $this->add_log('导入考试安排，插入了'. count($detailData). '条数据');

        exit(json($msg, true));
    }
    // 导入考场座位
    public function import_exam_seats() {
        $excelData = $this->_get_excel_data('考场名称', '座位号');
        $data = array();
        // 当roomname为空，使用上一个存在的detailid
        $detailId = '';
        foreach($excelData as $item) {
            $roomName = $item[0];
            $seatNo = $item[1];
            $realname = $item[2];
            $studentTicket = $item[3];
            // 获取学生
            $student = $this->schoolModel->get_student_info_by_realname($realname, $this->rmxSchool['id']);
            if(empty($student)) {
                throw new Exception('学生名称：' . $realname . ' 不存在!');
            }
            // 获取考场详情
            if($roomName) {
                $detail = $this->dataModel->get_exam_room_detail_info_by_room_name($roomName, $this->rmxSchool['id'], $this->campusInfo['id']);
                if(empty($detail)) {
                    throw new Exception('考场名称：' . $roomName . ' 不存在');
                }
                $detailId = $detail['id'];
            }
            $data[$detailId][] = array(
                'userID' => $student['id'],
                'seatNO' => $seatNo,
                'studentTicket' => $studentTicket
            );
         }
         $detailData = array();
         foreach($data as $key => $value) {
            $detailData[] = array(
                'id' => $key,
                'student_capacity' => count($value),
                'students' => json_encode($value, JSON_UNESCAPED_UNICODE)
            );
         }
        // 更新考场详情数据
        $this->db->update_batch(DataModel::$examRoomDetailTable, $detailData, 'id');
        $msg = '导入成功，';
        $msg .= '插入了' . count($detailData). '条数据';

        $this->add_log('导入考场座位，插入了'. count($detailData). '条数据');

        exit(json($msg, true));
    }
    // 导入年级成绩
    public function import_grade_result() {
        // 保留首行
        $excelData = $this->_get_excel_data('学生名称', '年级名称', false);
        // 获取首行数据
        $firstRowData = $excelData[1];
        // 去掉首行
        array_shift($excelData);
        // var_export($excelData);exit;
        $majorId = $this->post('major_id');
        if(empty($majorId)) {
            throw new Exception('major_id不能为空');
        }
        // 获取第一行年级名称
        $gradeName = $excelData[0][1];
        // 获取年级
        $grade = $this->classesModel->get_grade_info_by_name($gradeName, $this->rmxSchool['id'], $this->campusInfo['id']);
        if(empty($grade)) {
            throw new Exception('年级名称：' . $gradeName . ' 不存在!');
        }
        foreach($excelData as $item) {
            // 判断是否同个年级
            if($item[1] !== $gradeName) {
                throw new Exception('一次只能导入一个年级');
            }
        }
        $major = $this->dataModel->get_result_major_info($majorId);
        if(empty($major)) {
            throw new Exception('major_id不存在');
        }
        // 获取年级科目列表
        $subjectList = $this->schoolModel->get_lesson_list(array(
            'schoolId' => $this->rmxSchool['id'],
            'isDelete' => 0
        ));
        // 用科目名称作为键值
        $subjectList = array_value_to_key($subjectList, 'lesson_name');
        $subjectIdArr = array();
        $subjectIndexArr = array();
        foreach($firstRowData as $key => $subjectName) {
            if($key > 3) {
                if(!isset($subjectList[$subjectName])) {
                    throw new Exception('科目：' . $subjectName . '不存在');
                }
                array_push($subjectIdArr, $subjectList[$subjectName]['id']);
                $subjectIndexArr[$key] = array(
                    'subject_id' => $subjectList[$subjectName]['id'],
                    'subject_name' => $subjectName
                );
            }
        }
        // id从大到小排序
        sort($subjectIdArr);
        $subjectIds = implode(',', $subjectIdArr);

        // 通过年级名称获取年级项
        $resultGradeInfo = $this->dataModel->get_result_grade_info_by_grade_id($majorId, $grade['id']);
        // echo '<pre>';var_export($subjectIds);var_export($resultGradeInfo['subject_ids']);exit;
        if(empty($resultGradeInfo)) {
            // 年级项不存在，插入年级项
            $this->db->insert(DataModel::$resultGradeTable, array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'major_id' => $majorId,
                'grade_id' => $grade['id'],
                'show_grade_rank' => 0,
                'show_class_rank' => 0,
                'subject_ids' => $subjectIds,
                'is_delete' => 0,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')
            ));
            $resultGradeId = $this->db->insert_id();
        } else {
            $idArr = explode(',' ,$resultGradeInfo['subject_ids']);
            // id从大到小排序
            sort($idArr);
            $idStr = implode(',', $idArr);
            if($subjectIds != $idStr) {
                throw new Exception('与上次导入的科目冲突，请先删除旧数据');
            }
            // 年级项已存在
            $resultGradeId = $resultGradeInfo['id'];
        }
        // 获取本校全部学生
        $studentParams['schoolId'] = $this->rmxSchool['id'];
        $studentParams['campusId'] = $this->campusInfo['id'];
        // 过滤年级
         // 入库
         $classArr = $this->classesModel->get_class_list_by_grade($grade['id']);
         // 班级id集合
         $classIdArr = array();
         foreach($classArr as $class) {
             array_push($classIdArr, $class['id']);
         }
        $studentParams['classSet'] = implode(',', $classIdArr);
        $studentParams['isDelete'] = 0;
        $studentList = $this->schoolModel->get_student_list($studentParams);
        // $studentList = array_value_to_key($studentList, 'realname');
        $studentList = array_value_to_key($studentList, 'realname,seat_no');

        $data = array();
        foreach($excelData as $item) {
            // 学生名称
            $realname = trim($item[0]);
            // 座位号
            $seatNo = trim($item[3]);
            $studentIndex = $realname . $seatNo;
            if(!isset($studentList[$studentIndex])) {
                throw new Exception('学生：' . $realname . '，座位号：' . $seatNo . '，不存在');
            }
            $student = $studentList[$studentIndex];
            $valueArr = array();
            $total = 0;
            foreach($subjectIndexArr as $indexKey => $indexItem) {
                $score = $item[$indexKey];
                if($score < 0 || $score > 150) {
                    throw new Exception('分数不合法');
                }
                $indexItem['score'] = $score;
                $scoreArr = $indexItem;
                array_push($valueArr, $scoreArr);
                $total += $score;
            }
            // 按subjectid排序
            array_multisort(array_column($valueArr,'subject_id'), SORT_ASC, $valueArr);
            $value = json_encode($valueArr, JSON_UNESCAPED_UNICODE);
            // echo '<pre>';var_export($valueArr);exit;
            $data[] = array(
                'result_grade_id' => $resultGradeId,
                'student_id' => $student['id'],
                'value' => $value,
                'total' => $total,
                'is_delete' => 0,
                'updatetime' => date('Y-m-d H:i:s')
            );
        }
        // 获取年级全部成绩
        $resultParams['resultGradeId'] = $resultGradeId;
        $resultParams['isDelete'] = 0;
        $resultList = $this->dataModel->get_result_list($resultParams);
        $resultList = array_value_to_key($resultList, 'student_id');
        // 遍历接口所有数据
        $insertResultBatch = $updateResultBatch = array();
        foreach($data as $item) {
            // 更新还是新增
            if(isset($resultList[$item['student_id']])) {
                $item['id'] = $resultList[$item['student_id']]['id'];
                $updateResultBatch[] = $item;
            } else {
                $item['createtime'] = date('Y-m-d H:i:s');
                $insertResultBatch[] = $item;
            }
        }
        // 插入数据
        if(count($insertResultBatch)) {
            $this->db->insert_batch(DataModel::$resultTable, $insertResultBatch);
        }
        if(count($updateResultBatch)) {
            $this->db->update_batch(DataModel::$resultTable, $updateResultBatch, 'id');
        }
        $msg = '导入成功，';
        $msg .= '插入了' . count($insertResultBatch). '条数据';

        $this->add_log('导入成绩，插入了'. count($insertResultBatch). '条数据');

        exit(json($msg, true));
    }

    // 导入班牌对应班级
    public function import_brand_class() {
        $excelData = $this->_get_excel_data('班牌id');
        $data = array();
        foreach($excelData as $item) {
            $brandId = trim($item[0]);
            $className = trim($item[1]);
            if(empty($brandId)) {
                throw new Exception('班牌id不能为空');
            }

            $data[] = array(
                'brand_id' => $brandId,
                'class_name' => $className,
            );
        }
        // 获取本校全部班级
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'class_name');

        // 获取本校全部班牌
        $brandParams['schoolId'] = $this->rmxSchool['id'];
        $brandParams['isDelete'] = 0;
        $brandList = $this->classesModel->get_brand_list_left_join_class($brandParams);
        $brandList = array_value_to_key($brandList, 'id');
        // echo'<pre>'; var_export($brandList);exit;

        // 获取接口所有科目列表
        $updateBatch = array();
        foreach($data as $item) {
            $brandId = $item['brand_id'];
            $className = $item['class_name'];
            if(!isset($brandList[$brandId])) {
                throw new Exception('班牌id：' . $brandId . ' 不存在!');
            }
            if(empty($className)) {
                // 删除对应班级
                $classId = 0;
            } else {
                if(!isset($classList[$className])) {
                    throw new Exception('班级名称：' . $className . ' 不存在!');
                }
                $classId = $classList[$className]['id'];
            }
            
            // 更新
            $updateBatch[] = array(
                'id' => $brandId,
                'class_id' => $classId,
                'updatetime' => date('Y-m-d H:i:s')  
            );
            
        }
        // 插入数据
        if(count($updateBatch)) {
            $this->db->update_batch(ClassesModel::$brandTable, $updateBatch, 'id');
        }

        $msg = '导入成功';

        exit(json($msg, true));
    }
    
     // 导入班级排序值
     public function import_class_sort_level() {
        $excelData = $this->_get_excel_data('班级名称');
        $data = array();
        // echo'<pre>';var_export($excelData);exit;
        foreach($excelData as $item) {
            $className = trim($item[0]);
            $sortLevel = trim($item[1]) ? trim($item[1]) : 0;
    
            $data[] = array(
                'class_name' => $className,
                'sort_level' => $sortLevel,
            );
        }
        // 获取本校全部班级
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'class_name');
        $updateClassBatch = array();
        foreach($data as $item) {
            if(isset($classList[$item['class_name']])) {
                $item['id'] = $classList[$item['class_name']]['id'];
                $updateClassBatch[] = $item;
            }
        }
        if(count($updateClassBatch)) {
            $this->db->update_batch(ClassesModel::$classTable, $updateClassBatch, 'id');
        }
    
        $msg = '导入成功，';
        $msg .= '更新了' . count($updateClassBatch). '条数据';
        $this->add_log('导入班级排序值，更新了'. count($updateClassBatch). '条数据');
    
        exit(json($msg, true));
    }

    // 导入任课教师
    public function import_teacher_coach() {
        $this->load->model('gateModel');
        $excelData = $this->_get_excel_data('执教班级');
        // 获取本校全部老师
        $teacherParams['schoolId'] = $this->rmxSchool['id'];
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'realname');
        // 获取本校全部科目
        $lessonParams['schoolId'] = $this->rmxSchool['id'];
        $lessonParams['isDelete'] = 0;
        $lessonList = $this->schoolModel->get_lesson_list($lessonParams);
        $lessonList = array_value_to_key($lessonList, 'lesson_name');
        // 获取本校全部班级
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'class_name');
        $data = array();
        foreach($excelData as $item) {
            $className = trim($item[0]);
            $teacherName = trim($item[1]);
            $lessonName = trim($item[2]);
            if(isset($classList[$className])) {
                $classId = $classList[$className]['id'];
            } else {
                throw new Exception('班级名称不存在：' . $className);
            }
            if(isset($teacherList[$teacherName])) {
                $teacherId = $teacherList[$teacherName]['id'];
            } else {
                throw new Exception('教师名称不存在：' . $teacherName);
            }
            if(isset($lessonList[$lessonName])) {
                $lessonId = $lessonList[$lessonName]['id'];
            } else {
                throw new Exception('科目名称不存在：' . $lessonName);
            }
            $data[] = array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'class_ids' => $classId,
                'subject_ids' => $lessonId,
                'teacher_id' => $teacherId,
                'coach_type' => COACH_TYPE_TEACHER,
                'is_delete' => 0,
                'updatetime' => date('Y-m-d H:i:s') 
            );
        }
        // 判断该记录是否已存在
        $coachParams['schoolId'] = $this->rmxSchool['id'];
        $coachParams['campusId'] = $this->campusInfo['id'];
        $coachParams['coachType'] = COACH_TYPE_TEACHER;
        $coachList = $this->staffModel->get_coach_list($coachParams);
        $coachList = array_value_to_key_with_underline($coachList, 'class_ids,teacher_id,subject_ids');

        //获取全部行政班信息接口
        $insertBatch = $updateBatch = array();
        foreach($data as $item) {
            $uniqueId = $item['class_ids'] . "_" . $item['teacher_id'] . "_" . $item['subject_ids'];
            // 更新还是新增
            if(!isset($coachList[$uniqueId])) {
                $item['createtime'] = date('Y-m-d H:i:s');
                $insertBatch[] = $item;
            }
        }
        // 插入数据
        if(count($insertBatch)) {
            $this->db->insert_batch(StaffModel::$coachTable, $insertBatch);
        }
        // echo '<pre>';var_export($insertBatch);var_export($updateBatch);exit;
        $msg = '导入成功，';
        $msg .= '插入了' . count($insertBatch). '条数据';

        $this->add_log('导入任课老师，插入了'. count($insertBatch). '条数据');

        exit(json($msg, true));
    }
    // 导入班主任
    public function import_master_coach() {
        $this->load->model('gateModel');
        $excelData = $this->_get_excel_data('班主任班级');
        // 获取本校全部老师
        $teacherParams['schoolId'] = $this->rmxSchool['id'];
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'realname');
        // 获取本校全部班级
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classParams['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'class_name');
        $data = array();
        foreach($excelData as $item) {
            $className = trim($item[0]);
            $teacherName = trim($item[1]);
            if(isset($classList[$className])) {
                $classId = $classList[$className]['id'];
            } else {
                throw new Exception('班级名称不存在：' . $className);
            }
            if(isset($teacherList[$teacherName])) {
                $teacherId = $teacherList[$teacherName]['id'];
            } else {
                throw new Exception('教师名称不存在：' . $teacherName);
            }
            $data[] = array(
                'school_id' => $this->rmxSchool['id'],
                'campus_id' => $this->campusInfo['id'],
                'class_ids' => $classId,
                'teacher_id' => $teacherId,
                'coach_type' => COACH_TYPE_MASTER,
                'is_delete' => 0,
                'updatetime' => date('Y-m-d H:i:s') 
            );
        }
        // 判断该记录是否已存在
        $coachParams['schoolId'] = $this->rmxSchool['id'];
        $coachParams['campusId'] = $this->campusInfo['id'];
        $coachParams['coachType'] = COACH_TYPE_MASTER;
        $coachList = $this->staffModel->get_coach_list($coachParams);
        $coachList = array_value_to_key_with_underline($coachList, 'class_ids,teacher_id');

        //获取全部行政班信息接口
        $insertBatch = $updateBatch = array();
        foreach($data as $item) {
            $uniqueId = $item['class_ids'] . "_" . $item['teacher_id'];
            // 更新还是新增
            if(!isset($coachList[$uniqueId])) {
                $item['createtime'] = date('Y-m-d H:i:s');
                $insertBatch[] = $item;
            }
        }
        // 插入数据
        if(count($insertBatch)) {
            $this->db->insert_batch(StaffModel::$coachTable, $insertBatch);
        }
        // echo '<pre>';var_export($insertBatch);var_export($updateBatch);exit;
        $msg = '导入成功，';
        $msg .= '插入了' . count($insertBatch). '条数据';

        $this->add_log('导入班主任，插入了'. count($insertBatch). '条数据');

        exit(json($msg, true));
    }
    // 获取excel数据
    private function _get_excel_data($firstRowTitle='', $secondRowTitle='', $removeFirst=true) {
        $fileLink = $this->post('fileLink');
        // 暂时只支持xls
        $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($fileLink);
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $excelData = array();
        for ($row = 1; $row <= $highestRow; $row++) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $title = (string)$objWorksheet->getCellByColumnAndRow($col, 1)->getValue();
                $value = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                if(strstr($title, '日期')) {
                    // 转换日期
                    $excelData[$row][] = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($value));
                } elseif(strstr($title, '时间')) {
                    // 转换时间
                    $excelData[$row][] = date('H:i', PHPExcel_Shared_Date::ExcelToPHP($value) - 28800);
                } else {
                    $excelData[$row][] = $value;
                }
            }
        }
        if(empty($excelData)) {
            throw new Exception('该文件是空文件');
        }
        // 检验文件格式
        if($firstRowTitle) {
            if($firstRowTitle != $excelData[1][0]) {
                throw new Exception('表格格式不正确');
            }
        }
        if($secondRowTitle) {
            if($secondRowTitle != $excelData[1][1]) {
                throw new Exception('表格格式不正确');
            }
        }
        if($removeFirst) {
            // 去掉首行
            array_shift($excelData);
            if(empty($excelData)) {
                throw new Exception('有效数据为空');
            }
        }
        return $excelData;
    }

    // 插入日志
    private function add_log($content) {
         // 插入日志
         $this->load->library('logger');
         $actionType = $this->logger->get_action_type('import');
         $this->logger->save_log_action(array(
             'school_id' => $this->rmxSchool['id'],
             'campus_id' => $this->campusInfo['id'],
             'user_type' => $this->rmxUser['user_type'],
             'user_id' => $this->rmxUser['id'],
             'realname' => $this->rmxUser['realname'],
             'action_type' => $actionType,
             'content' => $content
         ));
    }
}